﻿using System;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

namespace Infrastructure.Mvc.SeedWork.Extensions
{
    public static class ObjectExtensions
    {
        /// <summary>
        ///     JSON序列化
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string JsonSerializer<T>(T t)
        {
            var serializer = new JavaScriptSerializer();
            string jsonStr = serializer.Serialize(t);
            ;
            string pattern = @"\/Date\((\d+)\+\d+\)\/";
            var matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            var reg = new Regex(pattern);
            jsonStr = reg.Replace(jsonStr, matchEvaluator);
            return jsonStr;
        }

        /// <summary>
        ///     将Json序列化的时间由/Date(1304931520336+0800)/转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            var dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }

        /// <summary>
        ///     将时间字符串转为Json时间
        /// </summary>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }

        public static string ToJson<T>(this T source)
        {
            return JsonSerializer(source);
        }

        //public static string ToJson(this object source)
        //{
        //    string serializedObject = string.Empty;

        //    if (source != null)
        //    {
        //        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(source.GetType());

        //        using (MemoryStream memStream = new MemoryStream())
        //        {
        //            jsonSerializer.WriteObject(memStream, source);
        //            memStream.Position = 0;
        //            serializedObject = new StreamReader(memStream).ReadToEnd();
        //        }
        //    }

        //    return serializedObject;
        //}

        //public static object FromJson(this Type type, string serializedObject)
        //{
        //    object filledObject = null;

        //    if (!string.IsNullOrEmpty(serializedObject))
        //    {
        //        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);

        //        using (MemoryStream memStream = new MemoryStream())
        //        {
        //            StreamWriter writer = new StreamWriter(memStream, Encoding.Default);
        //            writer.Write(serializedObject);
        //            writer.Flush();

        //            memStream.Position = 0;

        //            try
        //            {
        //                filledObject = dcjs.ReadObject(memStream);
        //            }
        //            catch (SerializationException)
        //            {
        //                filledObject = null;
        //            }
        //        }
        //    }

        //    return filledObject;
        //}

        /// <summary>
        ///     如果源对象为null，则返回null，否则返回其ToString方法返回值
        /// </summary>
        /// <param name="source">源对象</param>
        /// <returns>字符串</returns>
        public static string ToNullableString(this object source)
        {
            if (source == null)
                return null;
            return source.ToString();
        }

        ///// <summary>
        ///// 深度克隆
        ///// </summary>
        ///// <param name="source">源对象</param>
        ///// <returns>新对象</returns>
        //public static object DeepClone(this object source)
        //{
        //    if (source == null)
        //        return null;

        //    using (MemoryStream memStream = new MemoryStream())
        //    {
        //        BinaryFormatter binaryFormatter = new BinaryFormatter(null,
        //             new StreamingContext(StreamingContextStates.Clone));
        //        binaryFormatter.Serialize(memStream, source);
        //        memStream.Position = 0;
        //        return binaryFormatter.Deserialize(memStream);
        //    }
        //}
    }
}